<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户控制器
 * @author Calvin
 * @modified:2016/02/24
 */
require(APPPATH.'libraries/Web_Controller.php');
class User extends Web_Controller{
    private $_user_info = null;  //用户信息
    private $_find_pwd_user = "__FIND_PWD_USER__";
	private $_find_pwd_vcode = "__FIND_PWD_VCODE__";

	public function __construct() {
		parent::__construct();

		$this->load->model('user_model');
		$services = array(
			'user_info_service',
			'register_service',
			'user_verify_service',
            'login_service'
		);
		$this->load->service($services);
		$this->load->library("form_validation");
		$this->config->load("form_validation");
		$this->_user_info = $this->login_service->get_user_info();
	}

	/**
     * 登录
     * */
    public function login_post() {

        if ($this->session->has_userdata($this->_find_pwd_user))
        {
            $array_items = array($this->_find_pwd_code, $this->_find_pwd_user);
            $this->session->unset_userdata($array_items);
        }
        //获取账号
        $account = trim($this->input->post('account',TRUE));
        //检查合法性
        $phone_valid = $this->form_validation->valid_mobile_phone($account);
        $email_valid = $this->form_validation->valid_email($account);

        if( ! $account || !( $email_valid || $phone_valid))
        {
            return $this->common_response(1003);
        }
        //获取密码
        $password = trim($this->input->post('password',TRUE));

        if (empty($password))
        {
            return $this->common_response(1003);
        }


        $user = $email_valid ? $this->login_service->check_login_by_email($account, $password):
            $this->login_service->check_login_by_phone($account, $password);

        if ($user !== FALSE)
        {
            $this->login_service->login_by_data($user,0,0);
            return $this->common_response(0);
        }
        else
        {
            $error = $this->login_service->get_error();
            $this->login_service->add_login_error_log();
            $extra = array();
            //显示验证码
            if ($error['code'] == 5002 && $this->login_service->vcode_required())
            {
                $extra['show_vcode'] = true;
            }
            return $this->common_response($this->login_service,NULL,$extra,FALSE);
        }
    }

	/**
	 * 重置密码表单处理
	 * @return array
	 */ 
	public function reset_pwd_put(){

		$this->form_validation->set_rules('code','', 'required');
		$this->form_validation->set_rules('password','', 'required|valid_password');
		if($this->form_validation->run()==FALSE)
		{
			return $this->common_response(1003);
		}
		$pwd =  $this->put('password',TRUE);
		$code = $this->put("code",TRUE);
		//校验验证码并销毁
		$check_code = $this->user_verify_service->check_email_verify_code($code,"",User_verify_service::PROCESS_FIND_PASSWORD,TRUE,TRUE);
		if($check_code===FALSE)
		{
			return $this->common_response($this->user_verify_service);
		}
		$state = $this->user_info_service->update_user_info_by_email($check_code['receiver'], array('password' => md5($pwd)));
		if($state)
		{
			$this->login_service->logout();
			//Common::success('/login', '重置密码成功');
			return $this->common_response(0,NULL,array('redirect'=>"/find_pwd/reset_success"),FALSE);
		}
		else
		{
			return $this->common_response($this->user_info_service);
			//Common::error('重置密码失败');
		}

	}

	/**
	 * 找回密码表单处理
	 * @return array
	 */
	public function find_pwd_post() {
		$vcode = trim($this->input->post('vcode',TRUE));
		$account = trim($this->input->post('account',TRUE));
		if(empty($account) || empty($vcode))
		{
			return $this->common_response(1003);
		}
		if(strtoupper($vcode)!= $this->session->userdata($this->_find_pwd_vcode))
		{
			return $this->common_response(1007);
		}
		$valid_email = $this->form_validation->valid_email($account);
		$valid_mobile = $this->form_validation->valid_mobile_phone($account);
		if(!$valid_email && !$valid_mobile)
		{
			return $this->common_response(1003);
		}
		if($valid_email)
		{
			//$check = $this->user_verify_service->can_send_email($account,User_verify_service::PROCESS_FIND_PASSWORD,"");
			$check_user = $this->user_verify_service->check_user_by_email($account);
			//检查用户
			if($check_user===FALSE)
			{
				return $this->common_response($this->user_verify_service);
			}
		}
		else
		{
			//$check  = $this->user_verify_service->can_send_sms($account,2);
			$check_user = $this->user_verify_service->check_user_by_phone($account);
			//检查用户
			if($check_user===FALSE)
			{
				return $this->common_response($this->user_verify_service);
			}
		}
		/*if(!$check){
			return Common::ajax_return($this->user_verify_service);
		}*/
		//是否发送链接式验证邮箱
		//$send_link = $this->input->post("send_link");
		if($valid_email)
		{
			$send = $this->user_verify_service->send_email($account,User_verify_service::PROCESS_FIND_PASSWORD,"find_pwd/reset_pwd");
		}
		else
		{
			$send = $this->user_verify_service->send_sms($account,User_verify_service::PROCESS_FIND_PASSWORD);
		}

		if($send)
		{
			if($valid_email)
			{
				return $this->common_response(0,NULL,array("account_type"=>1,"redirect"=>"/find_pwd/send_email_success/".urlencode($account)),FALSE);
			}
			else
			{
				$this->session->set_userdata($this->_sms_step1,array("mobile"=>$account,"time"=>time()));
				return $this->common_response(0,NULL,array("account_type"=>2,"redirect"=>"/find_pwd/valid_mobile"),FALSE);
			}
		}
		else
		{
			return $this->common_response($this->user_verify_service);
		}
	}

	/**
	 * 修改个人资料
	 * @return array|void
	 */
	public function user_info_post() {
		if($this->form_validation->run('update_user_info')==FALSE) {
			return $this->common_response(1003);
		}
		$data = array(
				'nickname'     => trim($this->input->post('nickname', TRUE)),
				'company_name' => trim($this->input->post('company_name', TRUE)),
				'image' => trim($this->input->post('image', TRUE))
		);

		$old_image = $this->login_service->get_user_info("image");
		$old_image_path = $this->input->server("DOCUMENT_ROOT").$old_image;

		if($data['image']!=$old_image && file_exists($old_image_path)) {
			$this->user_info_service->clear_face_tmp(dirname($old_image_path),array($data['image'],$old_image));
		}
		//检查手机
		$n_mobile = trim($this->input->post('n_mobile',TRUE));
		if(!empty($n_mobile) && $this->register_service->check_phone_exists($n_mobile)) {
			return $this->common_response(5009);
		}
		else if(!empty($n_mobile))
		{
			$data['n_mobile'] = $n_mobile;
		}

		//检查邮件
		$n_email = trim($this->input->post('n_email',TRUE));
		if(!empty($n_email) && $this->register_service->check_email_exists($n_email))
		{
			return $this->common_response(5001);
		}
		else if(!empty($n_email))
		{
			$data['n_email'] = $n_email;
		}

		$this->user_info_service->update_user_info($this->_user_info['id'],$data);
		$this->login_service->reload_user_info();
		return $this->common_response(0);
	}

	/**
	 * 上传头像
	 */
	public function upload_img_put() {
		$image = $this->login_service->get_user_info("image");
		$upload = $this->user_info_service->upload_face($this->_user_info['id'],$image);

		if(!$upload) {
			return $this->common_response($this->user_info_service);
		}
		return $this->common_response(0,NULL,$upload,FALSE);
	}

    /**
     * 检查是否已经有绑定的email
     */
    private function check_old_email() {
		if($this->login_service->get_user_info("email")=="") {
			show_404();
		}
	}
    /**
     * 修改邮箱
     * @return array
     */
	public function send_new_email_post() {

		$this->check_old_email();
		$this->form_validation->set_rules('email','', 'required|valid_email');

		if (!$this->form_validation->run()) {
			return $this->common_response(1003);
		}
		$email = $this->input->post("email",TRUE);
        if($this->login_service->get_user_info("email")==$email) {
            return $this->common_response(5012);
        }

        $check = $this->register_service->check_email_exists($email);
        if($check) {
            return $this->common_response(5001);
        }

        $send = $this->user_verify_service->send_email($email,User_verify_service::PROCESS_MODIFY_EMAIL,"email_callback/valid_new_email",$this->_user_info['id'],TRUE);
        if(!$send) {
            return $this->common_response($this->user_verify_service);
        }
        return $this->common_response(0,NULL,array("redirect"=>"/user/send_new_email_success/".urlencode($email)),FALSE);
	}

	/**
	 * 验证手机
	 * @return array
	 */
	public function check_phone_post() {
		$this->form_validation->set_rules('mobile', '', 'required|valid_mobile_phone');
		if(!$this->form_validation->run()) {
			return $this->common_response(1003);
		}
		$phone = $this->input->post("mobile",TRUE);
		if($this->login_service->get_user_info("mobile")==$phone) {
			return $this->common_response(5011);
		}

		$check = $this->register_service->check_phone_exists($phone,$this->_user_info['id']);
		$ignore = $this->input->post("ignore",TRUE);
		if($check)
		{
			return $this->common_response(5009);
		}
		if(empty($ignore))
		{
			$can_send = $this->user_verify_service->can_send_sms($phone,User_verify_service::PROCESS_MODIFY_PHONE);
			if($can_send===FALSE)
			{
				$err_code =$this->user_verify_service->get_error("code");
				if($err_code==6003||$err_code==6004)
				{
					$error = $this->user_verify_service->get_error();
					return $this->common_response(0,$error['msg'],$error['info']);
				}
				else
				{
					return $this->common_response($this->user_verify_service);
				}
			}
		}
		return $this->common_response();
	}

	/**
	 * 检查邮箱有无已被注册
	 * @return array
	 */
	public function check_email_post()
	{
		$this->form_validation->set_rules('email','', 'required|valid_email');
		if($this->form_validation->run()==FALSE)
		{
			return $this->common_response(1003);
		}
		$email = trim($this->input->post('email',true));
		$userData = $this->register_service->check_email_exists($email);
		if($userData){
			if($userData['verify'] == 0){
				if($this->register_service->check_overdue_by_email($email)){
					return Common::ajax_return();
				} else {
					$data = Common::get_email_url($email);
					//self::ret_error(3, '该邮箱已被注册但没有激活', $data);
					return $this->common_response(5010,'',array("host"=>$data,"email"=>$email));
				}
			}
			return $this->common_response(5001);
		}
		return $this->common_response();
	}

	/**
	 * 发送验证手机号码短信
	 */
	public function send_valid_sms_post() {
		$this->form_validation->set_rules('mobile','', 'required|valid_mobile_phone');
		if ($this->form_validation->run() == FALSE)
		{
			return $this->common_response(1003);
		}
		else
		{
			$mobile = $this->input->post("mobile",TRUE);
			$check = $this->register_service->check_phone_exists($mobile);
			if($check)
			{
				return $this->common_response(5009);
			}
			$send = $this->user_verify_service->send_sms($mobile,User_verify_service::PROCESS_VALID_PHONE);
			if($send === FALSE)
			{
				return $this->common_response($this->user_verify_service);
			}
			return $this->common_response();
		}
	}

	/**
	 * 更换手机号码
	 * @return array
	 */
	public function save_new_phone_post() {
		$mobile = $this->input->post("mobile",TRUE);
		$code = $this->input->post("code",TRUE);

		if(empty($mobile) || empty($code))
		{
			return $this->common_response(1003);
		}

		$check = $this->user_verify_service->check_sms_code($code,$mobile,User_verify_service::PROCESS_VALID_PHONE,FALSE);
		if($check===FALSE)
		{
			return $this->common_response($this->user_verify_service);
		}
		else
		{
			$save = $this->user_info_service->update_user_info($this->_user_info['id'],array("mobile"=>$mobile,"n_mobile"=>""));
			if($this->login_service->is_login())
			{
				$this->login_service->reload_user_info();
			}
			if(!$save)
			{
				return $this->common_response($this->user_info_service);
			}

			return $this->common_response(0,NULL,array("redirect"=>"/user/valid_phone_success"),FALSE);
		}
	}

	/**
	 * 修改密码表单处理
	 * @return array
	 */
	public function do_update_pwd_post(){
		$this->form_validation->set_rules('old_password', '', 'required');
		$this->form_validation->set_rules('new_password', '', 'required');
		if(!$this->form_validation->run())
		{
			return $this->common_response(1003);
		}
		$old_pwd = md5($this->input->post('old_password'));
		$pwd = $this->login_service->get_user_info("password");
		if($old_pwd != $pwd)
		{
			return $this->common_response(5013);
		}
		//更新数据库
		$data = array(
			'password'	=> md5($this->input->post('new_password'))
		);
		if($this->user_info_service->update_user_info($this->_user_info['id'], $data))
		{
			//$this->register_service->logout();
			$this->login_service->reload_user_info();
			return $this->common_response(0,NULL,array("redirect"=>"/user/update_pwd_success"),FALSE);
		}
		else
		{
			return $this->common_response($this->user_info_service);
		}
	}

	/**
	 * 注册表单处理
	 * @return bool
	 */
	public function register_by_email_post(){
		//防止跨站恶意注册
		$uniqid = $this->input->post('uniqid',true);
		if(!$uniqid || $uniqid != $this->session->userdata('__UNIQID__')){
			show_404();
		}
		//验证表单
		if ($this->form_validation->run("register_by_email") == FALSE)
		{
			return $this->common_response(1003);
		}

		$email = trim($this->input->post('email', true));
		$password = $this->input->post('password',true);
		$n_phone = $this->input->post('n_phone',true);
		$register =$this->register_service->register_by_email($email,$password,$n_phone);

		if($register!==false)
		{
			$send = $this->user_verify_service->send_email($email,User_verify_service::PROCESS_REGISTER,"register/active");
			if($send)
			{
				//$this->send_email_success($email);
				return $this->common_response(0,'',array("redirect"=>"/register/send_email_success/".urlencode($email)));
			}
			else
			{
				return $this->common_response($this->user_verify_service);
			}
		}
		else
		{
			return $this->common_response($this->register_service);
		}
	}

	/**
	 * 验证手机验证码
	 * @return array
	 */
	public function check_sms_verify_code_post()
	{
		//$this->load->library('form_validation');
		$this->form_validation->set_rules('phone','', 'required|valid_mobile_phone');
		$this->form_validation->set_rules('sms_vcode','', 'required');
		//Common::console($this->form_validation->run());
		//var_dump($this->form_validation->run());
		if ($this->form_validation->run() == FALSE)
		{
			return $this->common_response(1003);
		}
		$code = $this->input->post("sms_vcode",TRUE);
		$phone = $this->input->post("phone",TRUE);
		$check =$this->user_verify_service->check_sms_code($code,$phone,User_verify_service::PROCESS_REGISTER,FALSE);
		if($check===FALSE)
		{
			return $this->common_response($this->user_verify_service);
		}
		return $this->common_response();
	}

	/**
	 * 手机号注册
	 * @return array
	 */
	public function register_by_phone_post()
	{
		$uniqid = $this->input->post('uniqid',true);
		if(!$uniqid || $uniqid != $this->session->userdata('__UNIQID__')){
			show_404();
		}

		if ($this->form_validation->run("register_by_phone") == FALSE)
		{
			return $this->common_response(1003);
		}

		//邮箱判断
		$phone = trim($this->input->post('phone', true));
		$password = $this->input->post('password',true);
		$n_email = $this->input->post('n_email',true);

		$sms_vcode = $this->input->post("sms_vcode",TRUE);
		if(!$this->user_verify_service->check_sms_code($sms_vcode,$phone,1,TRUE))
		{
			return $this->common_response($this->user_verify_service);
		}

		$register =$this->register_service->register_by_phone($phone,$password,$n_email);
		if($register!==false)
		{
			$this->register_service->delete_register_log();
			//销毁试用用户session
			//$this->login_service->logout();
			//$this->session->global_destroy($check['session_id']);
			//登录
			if(!empty($check['session_id']))
			{
				//销毁试用用户session
				$this->session->global_destroy($check['session_id']);
			}
			//卸载试用用户信息
			$this->login_service->unset_tryout();
			$this->login_service->login_by_uid($this->register_service->get_register_uid());
			return $this->common_response(0,NULL,array("redirect"=>"/files"));
		}
		else
		{
			return $this->common_response($this->register_service);
		}
	}

	/**
     * 退出
     */
    public function logout_get() {
        $this->login_service->logout();
        return $this->common_response($this->login_service);
    }
}